package com.fstec.ks.master.impl;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.List;
import java.util.concurrent.TimeUnit;

public class MasterChannelInitializer extends ChannelInitializer<SocketChannel>{
	private List<ChannelHandler> sharableHandlers;
	private boolean ssl=false;
	private int readIdleSeconds=0;
	private int writeIdleSeconds=0;

	public void setSsl(boolean ssl) {
		this.ssl = ssl;
	}

	public void setReadIdleSeconds(int readIdleSeconds) {
		this.readIdleSeconds = readIdleSeconds;
	}

	public void setWriteIdleSeconds(int writeIdleSeconds) {
		this.writeIdleSeconds = writeIdleSeconds;
	}

	public void setSharableHandlers(List<ChannelHandler> sharableHandlers) {
		this.sharableHandlers = sharableHandlers;
	}

	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline p = ch.pipeline();
		if (this.ssl) {
			SelfSignedCertificate ssc = new SelfSignedCertificate();
			SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
			p.addLast(sslCtx.newHandler(ch.alloc()));
		}
		if (this.readIdleSeconds>0 || this.writeIdleSeconds>0){
			p.addLast(new IdleStateHandler(this.readIdleSeconds, this.writeIdleSeconds, 0, TimeUnit.SECONDS));
		}
		if(null!=this.sharableHandlers){
			int size=this.sharableHandlers.size();
			for(int i=0;i<size;i++){
				p.addLast(this.sharableHandlers.get(i));
			}
		}
		p.addLast(new ChunkedWriteHandler());
		p.addLast(new MessageHandler());
	}
}
